<template>
  <el-form ref="dataForm" :model="formData" label-position="right" class="product-spec">
    <el-table
      v-show="formData.length > 0"
      ref="dataTable"
      v-loading="buildLoading"
      :data="formData"
      style="width: 100%"
      max-height="400px"
    >
      <el-table-column v-for="(item, index) in attrData" :key="index" :label="item.name" width="180">
        <template #default="scope">
          <el-form-item
            :prop="[scope.$index, 'productSpecAttrs', index, 'attrValue']"
            :rules="[{ required: true, message: `${item.name}不能为空` }]"
          >
            {{ formData[scope.$index].productSpecAttrs[index].attrValue }}
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template #default="scope">
          <IconifyIconOffline icon="ep:delete" class="cursor-pointer" @click="handleDelete(scope.$index, scope.row)" />
        </template>
      </el-table-column>
    </el-table>
  </el-form>
</template>
<script lang="ts" setup>
import {
  PropType,
  ref,
  shallowReactive,
  shallowRef,
  useTemplateRef,
  nextTick,
  onBeforeUpdate,
  onUpdated,
  watchEffect,
  watch
} from "vue";
import { useSubmitFormItem, MPageRegion as PageRegion, buildSubmitFormItem } from "page-com";
import { getCombinations } from "@/utils/utils";
const dataFormRef = useTemplateRef("dataForm");
const dataTableRef = useTemplateRef("dataTable");
const buildLoading = ref(false);
const { attrData, baseData } = defineProps({
  attrData: {
    type: Array as PropType<ShopProductAttrAddVo[]>,
    default: () => []
  },
  baseData: {
    type: Object,
    default: () => ({})
  }
});
const formData = ref<ShopProductSpecAddVo[]>([]);
const addSubmitFormItem = useSubmitFormItem();
const { validate, clear, getData, getKeys } = buildSubmitFormItem(formData, dataFormRef);
const handleDelete = (index: number, row: Attr) => {
  formData.value.splice(index, 1);
};
function getSepcData() {
  return { specs: getData() };
}
watch(
  () => attrData,
  () => {
    let arr: ShopProductAttrValueAddVo[][] = attrData.map(v => v.value);
    let des = getCombinations(arr);
    formData.value = [];
    for (let spec of des) {
      formData.value.push({
        specName: `${baseData.productName ?? ""} ${spec.map(v => v.attrValue).join()}`,
        productSpecAttrs: spec
      });
    }
  },
  { deep: true }
);
defineExpose({ clear, getData, validate });
addSubmitFormItem({ clear, getData: getSepcData, validate, getKeys });
</script>
<style lang="scss">
.product-spec-tplsel {
  font-size: small;
}
.product-spec .el-form-item {
  margin-bottom: 0px !important;
}
</style>
